package com.example.myblog.shiro;

import com.example.myblog.service.MUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    MUserService userService;

    //授权方法，凡是访问需要认证过的页面，都会执行这个授权方法
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录用户信息，
        AccountProfile profile = (AccountProfile) principalCollection.getPrimaryPrincipal();
        // 给id为2的admin赋予admin角色
        if(profile.getId() == 2) {
            //添加权限角色
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            info.addRole("admin");
            return info;
        }

        return null;
    }


    //登录时调用的方法
    //如果return null,会抛出异常
    //正常返回，当前用户就通过认证了
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        //强转类型
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        AccountProfile profile = userService.login(usernamePasswordToken.getUsername(), String.valueOf( usernamePasswordToken.getPassword()));

        //把结果放入Session域
        SecurityUtils.getSubject().getSession().setAttribute("profile", profile);
        System.out.println("放入session域了~~~");

        //getCredentials就是返回密码
        //如果info信息不对，shiro框架会帮我们抛出相应的异常
        //principal:认证的实体对象
        //credentials:密码
        //realmName:当前realm对象的name，调用父类的getName()即可
        //密码的比对由shiro完成，它会比对authenticationToken的password和参数credentials
        //我们这样写，这里肯定会通过认证
        //这里把profile存入，授权方法才可以获取到
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(profile, authenticationToken.getCredentials(), getName());
        return info;
    }
}
